<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">分类管理</h1>
    </div>

    <!-- 搜索和操作栏 -->
    <div class="table-toolbar">
      <div class="table-toolbar-left">
        <el-input
            v-model="searchForm.keyword"
            clearable
            placeholder="搜索分类名称"
            style="width: 200px"
            @clear="handleSearch"
            @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon>
              <Search/>
            </el-icon>
          </template>
        </el-input>

        <el-select
            v-model="searchForm.status"
            clearable
            placeholder="分类状态"
            style="width: 120px"
            @change="handleSearch"
        >
          <el-option :value="1" label="启用"/>
          <el-option :value="0" label="禁用"/>
        </el-select>

        <el-select
            v-model="searchForm.level"
            clearable
            placeholder="分类层级"
            style="width: 120px"
            @change="handleSearch"
        >
          <el-option :value="1" label="一级分类"/>
          <el-option :value="2" label="二级分类"/>
        </el-select>

        <el-button type="primary" @click="handleSearch">
          <el-icon>
            <Search/>
          </el-icon>
          搜索
        </el-button>

        <el-button @click="handleReset">
          <el-icon>
            <Refresh/>
          </el-icon>
          重置
        </el-button>
      </div>

      <div class="table-toolbar-right">
        <el-button type="primary" @click="handleCreate">
          <el-icon>
            <Plus/>
          </el-icon>
          添加分类
        </el-button>

        <el-button @click="handleRefresh">
          <el-icon>
            <Refresh/>
          </el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 分类表格 -->
    <div class="table-container">
      <el-table
          v-loading="loading"
          :data="categories"
          stripe
          style="width: 100%"
      >
        <el-table-column label="ID" prop="id" width="80"/>

        <el-table-column label="分类图标" width="80">
          <template #default="{ row }">
            <img
                v-if="row.icon"
                :src="row.icon"
                alt="分类图标"
                class="category-icon"
            />
            <el-icon v-else color="#ccc" size="24">
              <Picture/>
            </el-icon>
          </template>
        </el-table-column>

        <el-table-column label="分类名称" min-width="200">
          <template #default="{ row }">
          <span :style="{ paddingLeft: (row.level - 1) * 20 + 'px' }">
            {{ row.name }}
          </span>
          </template>
        </el-table-column>

        <el-table-column label="层级" prop="level" width="80">
          <template #default="{ row }">
            <el-tag :type="row.level === 1 ? 'primary' : 'success'" size="small">
              {{ row.level }}级
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="排序" prop="sortOrder" width="80"/>

        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="描述" min-width="150" prop="description">
          <template #default="{ row }">
            {{ row.description || '-' }}
          </template>
        </el-table-column>

        <el-table-column label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="200">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                  size="small"
                  type="primary"
                  @click="handleEdit(row)"
              >
                编辑
              </el-button>

              <el-button
                  v-if="row.status === 1"
                  size="small"
                  type="warning"
                  @click="handleUpdateStatus(row, 0)"
              >
                禁用
              </el-button>

              <el-button
                  v-else
                  size="small"
                  type="success"
                  @click="handleUpdateStatus(row, 1)"
              >
                启用
              </el-button>

              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 分类表单对话框 -->
    <CategoryFormDialog
        v-model="formDialogVisible"
        :category-id="selectedCategoryId"
        @success="handleFormSuccess"
    />
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Picture, Plus, Refresh, Search} from '@element-plus/icons-vue'
import {useCategoryStore} from '@/store/category'
import {formatDateTime} from '@/utils'
import CategoryFormDialog from './CategoryFormDialog.vue'

// 分类Store
const categoryStore = useCategoryStore()

// 响应式数据
const searchForm = reactive({
  keyword: '',
  status: null,
  level: null
})

const formDialogVisible = ref(false)
const selectedCategoryId = ref(null)

// 计算属性
const categories = computed(() => categoryStore.categories)
const loading = computed(() => categoryStore.loading)
const total = computed(() => categoryStore.total)
const currentPage = computed({
  get: () => categoryStore.currentPage,
  set: (value) => categoryStore.setPagination(value, categoryStore.pageSize)
})
const pageSize = computed({
  get: () => categoryStore.pageSize,
  set: (value) => categoryStore.setPagination(categoryStore.currentPage, value)
})

// 方法
const handleSearch = () => {
  categoryStore.setPagination(1, pageSize.value)
  loadCategoryList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: null,
    level: null
  })
  handleSearch()
}

const handleRefresh = () => {
  loadCategoryList()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  loadCategoryList()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadCategoryList()
}

const handleCreate = () => {
  selectedCategoryId.value = null
  formDialogVisible.value = true
}

const handleEdit = (category) => {
  selectedCategoryId.value = category.id
  formDialogVisible.value = true
}

const handleUpdateStatus = async (category, status) => {
  try {
    const action = status === 1 ? '启用' : '禁用'
    await ElMessageBox.confirm(
        `确定要${action}分类 "${category.name}" 吗？`,
        '确认操作',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    await categoryStore.updateCategoryStatus(category.id, status)
    ElMessage.success(`${action}成功`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新分类状态失败:', error)
      ElMessage.error('操作失败，请重试')
    }
  }
}

const handleDelete = async (category) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除分类 "${category.name}" 吗？此操作不可恢复！`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }
    )

    await categoryStore.deleteCategory(category.id)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分类失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

const handleFormSuccess = () => {
  formDialogVisible.value = false
  loadCategoryList()
}

const loadCategoryList = async () => {
  try {
    await categoryStore.getCategoryList(searchForm)
  } catch (error) {
    console.error('加载分类列表失败:', error)
    ElMessage.error('加载失败，请重试')
  }
}

// 生命周期
onMounted(() => {
  loadCategoryList()
})
</script>

<style scoped>
.page-container {
  padding: var(--admin-space-lg);
  background: var(--admin-bg-layout);
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: var(--admin-space-lg);
  padding: var(--admin-space-lg);
  background: var(--admin-bg-primary);
  border-radius: var(--admin-radius-lg);
  box-shadow: var(--admin-shadow-sm);
  border: 1px solid var(--admin-border-light);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  margin: 0;
  color: var(--admin-text-primary);
  font-size: var(--admin-font-xl);
  font-weight: var(--admin-font-semibold);
  line-height: var(--admin-line-height-sm);
}

.table-container {
  background: var(--admin-bg-primary);
  border-radius: var(--admin-radius-lg);
  box-shadow: var(--admin-shadow-sm);
  border: 1px solid var(--admin-border-light);
  overflow: hidden;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0;
  padding: var(--admin-space-lg);
  background: var(--admin-bg-secondary);
  border-bottom: 1px solid var(--admin-border-light);
}

.table-toolbar-left {
  display: flex;
  gap: var(--admin-space-sm);
  align-items: center;
  flex-wrap: wrap;
}

.table-toolbar-right {
  display: flex;
  gap: var(--admin-space-sm);
  align-items: center;
  flex-wrap: wrap;
}

.pagination-container {
  padding: var(--admin-space-lg);
  text-align: center;
  background: var(--admin-bg-secondary);
  border-top: 1px solid var(--admin-border-light);
}

/* 分类图标样式 */
.category-icon {
  width: 40px;
  height: 40px;
  border-radius: var(--admin-radius-sm);
  object-fit: cover;
  border: 1px solid var(--admin-border-light);
  transition: all 0.3s ease;
}

.category-icon:hover {
  border-color: var(--admin-primary);
  box-shadow: var(--admin-shadow-sm);
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: var(--admin-space-xs);
  align-items: center;
}

.action-buttons .el-button {
  padding: var(--admin-space-xs) var(--admin-space-sm);
  font-size: var(--admin-font-xs);
  height: var(--admin-height-sm);
  border-radius: var(--admin-radius-sm);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: var(--admin-space-md);
    align-items: flex-start;
  }

  .table-toolbar {
    flex-direction: column;
    gap: var(--admin-space-sm);
    align-items: stretch;
  }

  .table-toolbar-left,
  .table-toolbar-right {
    justify-content: center;
  }

  .action-buttons {
    flex-direction: column;
    width: 100%;
  }

  .action-buttons .el-button {
    width: 100%;
    justify-content: center;
  }
}
</style>
